package net.thxjj.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import net.model.device.DeviceBean;
import net.thxjj.extservice.MobileWebSocketClient;
import net.thxjj.service.IDeviceService;
import net.thxjj.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;

@Service
public class NettyServer {
    /**
     *
     */
    private Logger logger = Logger.getLogger(String.valueOf(this.getClass()));


    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IProductService productService;

    @Autowired
    private MobileWebSocketClient mobileWebSocketClient;

    @Value("${socket.port}")
    private int port;

    /**
     *
     */
    public void run(){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8))
                            .addLast(new DeviceRespChannelOutBoundHandler())
                            .addLast(new IdleStateHandler(1, 0,0))
                            .addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()))
                            .addLast(new StringDecoder(CharsetUtil.UTF_8))
                            .addLast(new SpliterHandler(deviceService,productService,mobileWebSocketClient));
                }
            });
            //band port
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            logger.info("netty服务启动: [port:" + port + "]");
            //wait for socket close
            channelFuture.channel().closeFuture().sync();

        }catch(Exception exception){
            logger.info("netty服务启动异常-" + exception.getMessage());
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String args[]){
         new NettyServer().run();
    }
}

